package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.bean.*;
import com.itheima.common.PageParam;
import com.itheima.dao.OrderDao;
import com.itheima.dto.OrdersDto;
import com.itheima.service.*;
import com.itheima.utils.BaseContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
@Transactional
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderDao orderDao;

    @Autowired
    private HttpSession session;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private OrderDetailService orderDetailService;


    /**
     * 提交订单
     *   1. 提交订单其实是一种添加的行为，但是它要往两张表里面添加数据： orders 和 order_detail
     *
     *   2. 先添加 orders 表、
     *      2.1 才能得到订单的id主键
     *
     *   3. 再添加order_detail 表
     *      3.1 给订单详情设置 订单id主键
     *
     * @param order
     * @return
     */
    @Override
    public int add(Orders order) {
        //1. 先添加订单表

        //1.1 设置订单号
        // 获取用户信息
        User user = (User) session.getAttribute("user");

        //获取地址信息
        AddressBook addressBook = addressBookService.getById(order.getAddressBookId());

        order.setNumber(UUID.randomUUID().toString().replace("-" , ""));
        //1.2 设置状态值 : 1 : 未付款，2： 已付款，待派送 ...
        order.setStatus(1);
        //1.3 设置用户id
        order.setUserId(user.getId());
        //1.4 设置地址id【页面提供了，不需要设置】
        //1.5 设置下单时间
        order.setOrderTime(LocalDateTime.now());
        //1.6 设置支付时间
        order.setCheckoutTime(LocalDateTime.now());
        //1.7 设置支付方式【页面提供了，不需要设置】
        //1.8 设置总金额 【页面提供了，不需要设置】
        //1.9 设置备注【页面提供了，不需要设置】
        //1.10 设置收货电话
        order.setPhone(addressBook.getPhone());
        //1.11 设置收货地址
        String address = ( addressBook.getProvinceName() != null ? addressBook.getProvinceName() : "" )
                + ( addressBook.getCityName() != null ? addressBook.getCityName() : "" )
                + ( addressBook.getDistrictName() != null ? addressBook.getDistrictName() : "" )
                + ( addressBook.getDetail() != null ? addressBook.getDetail() : "" );
        order.setAddress(address);

        //1.12 设置下单的用户名称
        order.setUserName(user.getName());
        //1.13 设置收货人名称
        order.setConsignee(addressBook.getConsignee());

        //1.1 补充数据
        //1.2 执行添加
        int row1 = orderDao.insert(order);

        //2. 再添加订单详情表 :: 详情表的数据，页面没有提供，购买的详细内容，其实就是购物车的内容。

        //2.1 获取当前用户的购物车数据
        List<ShoppingCart> cartList = shoppingCartService.list();
        int row2 = 0 ;
        if(cartList != null && cartList.size() >  0){
            //2.2 遍历每一个购物车数据
            for (ShoppingCart shoppingCart : cartList) {

                //2.3 遍历一次，构建一个订单详情对象！
                OrderDetail orderDetail = new OrderDetail();


                //2.4 把购物车的数据拷贝到订单详情对象
                BeanUtils.copyProperties(shoppingCart , orderDetail);

                //2.5 设置订单id
                orderDetail.setOrderId(order.getId());

                //2.6 添加到订单详情表
                row2 += orderDetailService.add(orderDetail);

            }
            return row2 == cartList.size() ? 1 : 0;
        }

        return row1;
    }

    /**
     * 订单分页查看
     * 何先晓
     * @param pageParam
     * @return
     */
    @Override
    public IPage findByPage(PageParam pageParam) {

        IPage<Orders> ordersIPage = new Page<>(pageParam.getPage(),pageParam.getPageSize());
        LambdaQueryWrapper<Orders> qw = new LambdaQueryWrapper<>();
        qw.like(pageParam.getNumber()!=null, Orders::getNumber,pageParam.getNumber());
        qw.between(pageParam.getBeginTime()!=null&&pageParam.getEndTime()!=null, Orders::getOrderTime,pageParam.getBeginTime(),pageParam.getEndTime());

        return orderDao.selectPage(ordersIPage,qw);
    }
     * 前台用户查询最新订单
     *
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public IPage<OrdersDto> userPage(int page, int pageSize) {
        User user = (User) session.getAttribute("user");
        Long id = user.getId();
        //查询orders
        LambdaQueryWrapper<Orders> lqw=new LambdaQueryWrapper<>();
        lqw.eq(Orders::getUserId,id);
        lqw.orderByDesc(Orders::getOrderTime);
        IPage<Orders> page1=new Page<>(page,pageSize);
        orderDao.selectPage(page1,lqw);
        List<Orders> ordersList = page1.getRecords();
        IPage<OrdersDto> iPage=new Page<>();
        List<OrdersDto> dtoList=new ArrayList<>();
        for (Orders orders : ordersList) {
            List<OrderDetail> orderDetails = orderDetailService.userPage(orders.getId());
            OrdersDto ordersDto = new OrdersDto();
            ordersDto.setOrderDetails(orderDetails);
            BeanUtils.copyProperties(orders,ordersDto);
            dtoList.add(ordersDto);
        }
            iPage.setRecords(dtoList);
        iPage.setTotal(page1.getTotal());
        return iPage;
    }


}
